package com.nd.rj.common.login;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.common.StarAppConfig;
import com.common.utils.EncryptTool;
import com.nd.rj.common.R;
import com.nd.rj.common.util.http.HttpTool4Byte;
import com.product.android.business.ApplicationVariable;

/**
 * ClassName:NdLogin99Assistant
 * Function: 登录99帐号中心相关参数的编码、解码
 * Reason:	 在V1.1之后要采用更加严谨的登录方式以防止恶意攻击，原来的json串形式登录到UAP要改成字节流的形式先登录到
 * 91帐号中心，获取到cookie之后再用这个cookie再登录到UAP或者OAP
 * 
 * @author   cb
 * @version  
 * @since    Ver 1.1
 * @Date	 2013	2013-5-23		下午2:37:54
 *
 * @see 	 
 */
public class NdLogin99Assistant {
	public final static int TIMESTAMP_ERROR=11009;
	public final static int TALK_EXPIRED=20005;
	public final static int RESPONSE_TYPE_ERROR=11000;
	public  final static int DATA_TYPE_INIT = 13001;
	public  final static int DATA_TYPE_LOGIN = 13002;
	public  final static int DATA_TYPE_GET_CHECKCODE = 13003;
	public final static int ERR_TYPE_IMG_CODE_ERR = 20054;
	public  final static int SEND_MSG_CODE_LIMITED = 30313;
	/**使用短信验证码登录*/
    public  final static int DATA_TYPE_MSG_LOGIN= 13005;
    
	/**发送短信验证码*/
	public  final static int DATA_TYPE_SEND_MSG_CODE = 13007;
	
	/**指示需要输入图形验证码*/
//    public  final static int ERR_NEED_INPUT_CHECK_CODE = 5858;
    
    /**发送短信登录时的短信验证码成功标识码*/
    private  final static int SEND_MSG_CODE_SUCCESS = 30310;
  
	
	public  final static int DATA_TYPE_INIT_RESPONSE = 14001;
	public  final static int DATA_TYPE_LOGIN_RESPONSE = 14002;
	public  final static int DATA_TYPE_GET_CHECKCODE_RESPONSE = 14003;
	private  final static int INIT_SUCCESS=20180;
    private  final static int GET_CHECKCODE_SUCCESS=20182;
	private  final static int LOGIN_SUCCESS=20050;
	private  final static String tag="debug";
	private  final static int ENCODE_TYPE = 1;
	private  final String KEY = "reg91com";
	private BitmapDrawable mDrawable;
	private long mTimeGap=0;
	private long mStartTime;
	private int mSiteFlat=0;
	private String mTalkCode;			//会话编号
	private String mKey;				//DES密钥
	private String mCookie;				//91登录之后得到的cookie
	private boolean mbIsInitSuccessful=false;//是否初始化成功
	private boolean mbInitializing=false;	//正在初始化
	private HttpTool4Byte mHttpTool;
	private Context mContext;
	private String mErrMsg="";
	private int mErrorCode=0;
	
	private final static String ExType = "SDKLogin";//明星APP 需接入SDK充值登录
    private String mToken; //与SDK登录用的
	
	public NdLogin99Assistant(Context context){
		mSiteFlat=GlobalSetting.getInstance(context).getSiteflat();
		mHttpTool=new HttpTool4Byte(context);
//		mContext=context.getApplicationContext();
		mContext = context;
	}
	
	public int getErrorCode(){
		return mErrorCode;
	}
	
	public boolean isInitializing(){
		return mbInitializing;
	}
	
	public boolean isInitSuccessful(){
		return mbIsInitSuccessful;
	}
	
	public boolean isNeedInit(){
		return 	   mErrorCode == NdLogin99Assistant.TALK_EXPIRED
				|| mErrorCode == NdLogin99Assistant.RESPONSE_TYPE_ERROR
				|| mErrorCode == NdLogin99Assistant.TIMESTAMP_ERROR;
	}
	
	public String getErrmsg(){
		return mErrMsg;
	}
	
	public String getCookie(){
		return mCookie;
	}
	
	public String getToken(){
        return mToken;
    }
	
	public int doInit(){
		mbInitializing=true;
		mErrorCode=doRequest(DATA_TYPE_INIT, null, null);
		getErrmsgFromCode(mErrorCode);
		if (mErrorCode==TIMESTAMP_ERROR){
			//时间戳不正确，重新初始化一次
			mErrorCode=doRequest(DATA_TYPE_INIT, null, null);
			getErrmsgFromCode(mErrorCode);
		}
		mbInitializing=false;		
		mbIsInitSuccessful=mErrorCode==0;
		//Log.d(tag, "init used:"+(System.currentTimeMillis()-start));
		return mErrorCode;
	}
	
	public int doGetCheckcode(){
		mErrorCode=doRequest(DATA_TYPE_GET_CHECKCODE, null, null);
		getErrmsgFromCode(mErrorCode);
		return mErrorCode;
	}
	
	public int doLogin(String account,String psw){
		return doLogin(account, psw, "");
	}
	
	public int doLogin(String account,String psw,String checkcode){
		if (checkcode==null){
			checkcode="";
		}
		mErrorCode=doRequest(DATA_TYPE_LOGIN, account, psw,checkcode);
		getErrmsgFromCode(mErrorCode);
		return mErrorCode;
	}
		
	/**
	 * 处理发送短信登录所需的短信验证码
	 * 
	 * <br>Created 2014-9-4 下午3:44:22
	 * @param strMobile        手机号
	 * @param strCheckCode     验证码，可能为空
	 * @return                 处理结果状态码
	 * @author       linsj
	 */
	public int doSendMsgCode(String strMobile, String strCheckCode){
	    mErrorCode=doRequest(DATA_TYPE_SEND_MSG_CODE, strMobile, "", strCheckCode);
        getErrmsgFromCode(mErrorCode);
        return mErrorCode;
    }
	
	/**
	 * 短信登录
	 * 
	 * <br>Created 2014-9-5 上午11:57:00
	 * @param strMobile        手机号码
	 * @param strMsgCheckCode  短信验证码
	 * @return                 操作结果
	 * @author       linsj
	 */
	public int doMsgLogin(String strMobile, String strMsgCheckCode){
        mErrorCode=doRequest(DATA_TYPE_MSG_LOGIN, strMobile, strMsgCheckCode);
        getMsgLoginErrmsgFromCode(mErrorCode);
        return mErrorCode;
    }
	
	private int doRequest(int type,String account,String psw){
		return doRequest(type, account, psw, "");
	}
	
	/**
	 * 处理登录的各种请求
	 * 
	 * <br>Created 2014-9-5 上午11:30:27
	 * @param type         请求类型
	 * @param account      帐号/密码
	 * @param psw          密码/短信验证码（短信登录时）
	 * @param checkcode    图形验证码
	 * @return             请求结果
	 * @author       linsj
	 */
	private int doRequest(int type,String account,String psw,String checkcode){
		byte[] param = null;
		if (type==DATA_TYPE_INIT){
			param=getInitParam();
		}else if (type==DATA_TYPE_GET_CHECKCODE){
			param=getCheckCodeParam();
		}else if (type==DATA_TYPE_SEND_MSG_CODE){
            param=getMsgCodeParam(account, checkcode);
        }else if(DATA_TYPE_LOGIN == type) {
			param=getLoginParam(account, psw,checkcode);
		}else if(DATA_TYPE_MSG_LOGIN == type){
		    param = getMsgLoginParam(account, psw, checkcode);
		}
		if (param==null){
			return -1;
		}
		StringBuffer receive=new StringBuffer();
		ArrayList<InputStream> data=new ArrayList<InputStream>();
		int result=mHttpTool.DoPost(param, receive,data);
		if (result!=0){
			if (result==R.string.nd_unknow_error){
				mErrMsg=receive.toString();
				result=-1;
			}
			return result;
		}
		if (data.size()>0){
			InputStream inputStream=data.get(0);
			if (inputStream!=null){
				try {
				    int respone_type = type+1000;
				    if(DATA_TYPE_MSG_LOGIN == type){
				        respone_type = DATA_TYPE_LOGIN + 1000;
				    }
				    
					result = decode(inputStream, type, respone_type);
				} catch (Exception e) {
					mErrMsg="doRequest "+type+","+e.getMessage();
				} finally{
					try {
						inputStream.close();
					} catch (IOException e) {
						mErrMsg="close inputstream "+type+","+e.getMessage();
					}
				}
				return result;
			}
		}
		return -1;
	}
	
	/**
	 * 填充通用参数段
	 * 
	 * <br>Created 2014-9-3 下午7:39:26
	 * @param iType        数据包类型型
	 * @param buffer       数据包字节流
	 * @param iSiteFlat    登录平台
	 * @param byteTalk     会话编号
	 * @author       linsj
	 */
	private void getParamSection(int iType, ByteArrayBuffer buffer, int iSiteFlat, byte[] byteTalk){
	    if(null == buffer){
	        return;
	    }
	    
        // 包类型
        EncryptTool.appendIntToByteArrayBuffer(iType, 2, buffer);
        // 时间戳
        mStartTime = System.currentTimeMillis() / 1000;
        long timeStamp = mStartTime + mTimeGap;
        EncryptTool.appendLongToByteArrayBuffer(timeStamp, 4, buffer);
        
        // 会话编号
        buffer.append(byteTalk, 0, byteTalk.length);
        // 平台
        EncryptTool.appendIntToByteArrayBuffer(iSiteFlat, 2, buffer);
        // 加密方式
        EncryptTool.appendIntToByteArrayBuffer(ENCODE_TYPE, 1, buffer);
	}
	
	/**
	 * 获取初始化需要填充的参数
	 * 
	 * <br>Created 2014-9-3 下午9:41:38
	 * @return        初始化需要填充的参数，字节流
	 * @author       linsj
	 */
	private  byte[] getInitParam(){
		int dataType = DATA_TYPE_INIT;
		
		ByteArrayBuffer buffer = new ByteArrayBuffer(49);
		
		//填充通用参数段
		byte[] bTalk = {0,0,0,0,0,0,0,0};
		getParamSection(dataType, buffer, mSiteFlat, bTalk);

		//签名
		String signature = dataType +""+ (mStartTime + mTimeGap) +""+ mSiteFlat +"" +ENCODE_TYPE+ KEY;
		signature=EncryptTool.getMD5str(signature,EncryptTool.TYPE_NORMAL).toLowerCase();
		byte[] bSignature = signature.getBytes();
		buffer.append(bSignature,0,bSignature.length);
		
		return buffer.toByteArray();
	}
	
	/**
     * 重新取验证码需要填充的参数
     * 
     * <br>Created 2014-9-3 下午9:41:38
     * @return        重新取验证码需要填充的参数，字节流
     * @author       linsj
     */
	public byte[] getCheckCodeParam(){
		int dataType=DATA_TYPE_GET_CHECKCODE;
		ByteArrayBuffer buffer = new ByteArrayBuffer(49);
		
		//填充通用参数段
		getParamSection(dataType, buffer, mSiteFlat, mTalkCode.getBytes());
        
		//签名
        String signature = dataType + "" + (mStartTime + mTimeGap) + mTalkCode + mSiteFlat + ""
                + ENCODE_TYPE + mKey;
		signature=EncryptTool.getMD5str(signature,EncryptTool.TYPE_NORMAL).toLowerCase();
		byte[] bSignature = signature.getBytes();
		buffer.append(bSignature,0,bSignature.length);
		
		return buffer.toByteArray();
	}
	
	/**
	 * 填充加密后的数据
	 * 
	 * <br>Created 2014-9-3 下午7:50:37
	 * @param buffer       数据包字节流
	 * @param strData      待加密的数据
	 * @return             成功时：加密后的数据，失败时：null
	 * @author       linsj
	 */
	private String getEncryptData(ByteArrayBuffer buffer, String strData){
        if (null == buffer) {
            return null;
        }
        
        // 加密后的数据字节流
        byte[] byteEncryptedData = null;
        try {
            byteEncryptedData = EncryptTool.desEncrypt(strData, mKey);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            mErrMsg = "error occor while encrypt account:" + strData + "," + e.getMessage();
            return null;
        }
        
        // 加密后的数据长度：DES加密后的长度是动态的，可能是16，也可能是32
        int iEncDataLen = byteEncryptedData.length * 2;
        EncryptTool.appendIntToByteArrayBuffer(iEncDataLen, 2, buffer);
        
        String strDescryptData = EncryptTool.byte2Hex(byteEncryptedData);
        byteEncryptedData = strDescryptData.getBytes();
        
        buffer.append(byteEncryptedData, 0, byteEncryptedData.length);
        
        return strDescryptData;
    }
	
	/**
	 * 获取登录需要填充的参数
	 * 
	 * <br>Created 2014-9-3 下午9:44:13
	 * @param account      帐号
	 * @param psw          混淆过的密码，再做MD5摘要
	 * @param checkcode    验证码
	 * @return             字节流的参数
	 * @author       linsj
	 */
    private byte[] getLoginParam(String account, String psw, String checkcode) {
        // 登录时参数集：[数据类型]13002 [时间戳]1368685696 [会话编号]01074635 [登录平台]999
        // [加密方式]1 [返回类型]110 [帐号]607067 [密码]e83454e7429fff4e72a5a2ddce4d198e
        // [验证码] [签名]c1ed8b512dc8ea5252ad3e5215f6c948
        int dataType = DATA_TYPE_LOGIN;
        ByteArrayBuffer buffer = new ByteArrayBuffer(169);

        // 填充通用参数段
        getParamSection(dataType, buffer, mSiteFlat, mTalkCode.getBytes());
        Log.w("msg_login", "send_msg talk code " + mTalkCode);

        // 游戏编号：固定传60001用于标识UAP
        int gameId = 60001;
        EncryptTool.appendIntToByteArrayBuffer(gameId, 2, buffer);

        // 填充帐号
        String strDesAccount = getEncryptData(buffer, account);
        if (null == strDesAccount) {
            return null;
        }

        // 加密后的密码
        // byte[] bMd5Psw=EncryptTool.getMD5Byte(psw, EncryptTool.TYPE_PSW);
        // String md5Psw=EncryptTool.byte2Hex(bMd5Psw).toLowerCase();
        // String md5Psw="8cfdc82e3dd15962ad54d903fc9c3abb";
        String strDesPSW = getEncryptData(buffer, psw);
        if (null == strDesPSW) {
            return null;
        }

        // 填充验证码
        String strDesCheckCode = getEncryptData(buffer, checkcode);
        if (null == strDesCheckCode) {
            return null;
        }

        // 签名
        String signature = dataType + "" + (mStartTime + mTimeGap) + mTalkCode + mSiteFlat + ""
                + ENCODE_TYPE + strDesAccount + strDesPSW + strDesCheckCode + mKey;
        signature = EncryptTool.getMD5str(signature, EncryptTool.TYPE_NORMAL).toLowerCase();
        byte[] bSignature = signature.getBytes();
        buffer.append(bSignature, 0, bSignature.length);
        
        
        // TODO 充值模块 启用：注释去掉
        //用于支付SDK登录获取的参数
        //"{\"ExType\":\"SDKLogin\",\"IMEI\":\"abcd\",\"LoginTime\":\"2014-11-11 11:00:00\"}";
        TelephonyManager tm = (TelephonyManager) (ApplicationVariable.INSTANCE.applicationContext.getSystemService(Context.TELEPHONY_SERVICE));
        String IMEI = tm.getDeviceId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String SDKLoginParam = "{\"ExType\":\"" + ExType + "\"," +
        		"\"IMEI\":\"" + IMEI + "\"," +
        		"\"LoginTime\":\"" + sdf.format(new Date()) + "\"}";
        String strSDKLoginParam = getEncryptData(buffer, SDKLoginParam);
        if (null == strSDKLoginParam) {
            return null;
        }
        
        return buffer.toByteArray();
    }
    
	/**
	 * 获取短信验证码登录时，要发送的请求数据
	 * 
	 * <br>Created 2014-9-3 下午5:30:03
	 * @param strMobile        手机号
	 * @param strCheckCode        验证码
	 * @return                 获取验证码需要填充的参数，字节流
	 * @author                 linsj
	 */
	private byte[] getMsgCodeParam(String strMobile, String strCheckCode){
	    // 登录时参数集：[数据类型]13002 [时间戳]1368685696 [会话编号]01074635 [登录平台]999
        // [加密方式]1 [返回类型]110 [帐号]607067 [密码]e83454e7429fff4e72a5a2ddce4d198e
        // [验证码] [签名]c1ed8b512dc8ea5252ad3e5215f6c948
        int dataType = DATA_TYPE_SEND_MSG_CODE;
        ByteArrayBuffer buffer = new ByteArrayBuffer(169);

        // 填充通用参数段
        getParamSection(dataType, buffer, mSiteFlat, mTalkCode.getBytes());
        Log.w("msg_login", "send_msg talk code " + mTalkCode);

        // 游戏编号：固定传60001用于标识UAP
        int gameId = 60001;
        EncryptTool.appendIntToByteArrayBuffer(gameId, 2, buffer);

        // 填充手机号
        String strDesAccount = getEncryptData(buffer, strMobile);
        if (null == strDesAccount) {
            return null;
        }

        // 填充验证码
        String strDesCheckCode = getEncryptData(buffer, strCheckCode);
        if (null == strDesCheckCode) {
            return null;
        }

        // 签名
        String signature = dataType + "" + (mStartTime + mTimeGap) + mTalkCode + mSiteFlat + ""
                + ENCODE_TYPE + gameId + "" + strDesAccount + strDesCheckCode + mKey;
        signature = EncryptTool.getMD5str(signature, EncryptTool.TYPE_NORMAL).toLowerCase();
        byte[] bSignature = signature.getBytes();
        buffer.append(bSignature, 0, bSignature.length);
        return buffer.toByteArray();
    }
	
	/**
     * 填充短信登录时，要发送的请求数据
     * 
     * <br>Created 2014-9-3 下午5:30:03
     * @param strMobile        手机号
     * @param strMsgCheckCode  短信验证码
     * @param strImgCheckCode  图形验证码
     * @return                 获取短信登录需要填充的参数，字节流
     * @author                 linsj
     */
    private byte[] getMsgLoginParam(String strMobile, String strMsgCheckCode, String strImgCheckCode){
        // 登录时参数集：[数据类型]13002 [时间戳]1368685696 [会话编号]01074635 [登录平台]999
        // [加密方式]1 [返回类型]110 [帐号]607067 [密码]e83454e7429fff4e72a5a2ddce4d198e
        // [验证码] [签名]c1ed8b512dc8ea5252ad3e5215f6c948
        int dataType = DATA_TYPE_MSG_LOGIN;
        ByteArrayBuffer buffer = new ByteArrayBuffer(169);

        // 填充通用参数段
        getParamSection(dataType, buffer, mSiteFlat, mTalkCode.getBytes());
        Log.w("msg_login", "send_login talk code " + mTalkCode);

        // 游戏编号：固定传60001用于标识UAP
        int gameId = 60001;
        EncryptTool.appendIntToByteArrayBuffer(gameId, 2, buffer);

        // 填充帐号
        String strDesAccount = getEncryptData(buffer, strMobile);
        if (null == strDesAccount) {
            return null;
        }

        // 加密后的短信验证码
        // byte[] bMd5Psw=EncryptTool.getMD5Byte(psw, EncryptTool.TYPE_PSW);
        // String md5Psw=EncryptTool.byte2Hex(bMd5Psw).toLowerCase();
        // String md5Psw="8cfdc82e3dd15962ad54d903fc9c3abb";
        String strDesMsgCheckCode = getEncryptData(buffer, strMsgCheckCode);
        if (null == strDesMsgCheckCode) {
            return null;
        }

        // 填充图形验证码
        String strDesImgCheckCode = getEncryptData(buffer, strImgCheckCode);
        if (null == strDesImgCheckCode) {
            return null;
        }

        // 签名
        String signature = dataType + "" + (mStartTime + mTimeGap) + mTalkCode + mSiteFlat + ""
                + ENCODE_TYPE + strDesAccount + strDesMsgCheckCode + strDesImgCheckCode + mKey;
        signature = EncryptTool.getMD5str(signature, EncryptTool.TYPE_NORMAL).toLowerCase();
        byte[] bSignature = signature.getBytes();
        buffer.append(bSignature, 0, bSignature.length);
        
        // TODO 充值模块 启用：注释去掉
        //用于支付SDK登录获取的参数
        //"{\"ExType\":\"SDKLogin\",\"IMEI\":\"abcd\",\"LoginTime\":\"2014-11-11 11:00:00\"}";
        TelephonyManager tm = (TelephonyManager) (ApplicationVariable.INSTANCE.applicationContext.getSystemService(Context.TELEPHONY_SERVICE));
        String IMEI = tm.getDeviceId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String SDKLoginParam = "{\"ExType\":\"" + ExType + "\"," +
                "\"IMEI\":\"" + IMEI + "\"," +
                "\"LoginTime\":\"" + sdf.format(new Date()) + "\"}";
        String strSDKLoginParam = getEncryptData(buffer, SDKLoginParam);
        if (null == strSDKLoginParam) {
            return null;
        }
        
        return buffer.toByteArray();
    }
	
	public  int decode(InputStream inputStream,int type,int respone_type) throws IOException,Exception{
		int code=getIntFromStream(inputStream, 2);
		if (code!=respone_type){
			//不是预期的返回值
			mErrMsg=mContext.getString(R.string.assistant_sever_packet_error);
			return RESPONSE_TYPE_ERROR;
		}
		long timestamp=getLongFromStream(inputStream, 4);
		mTimeGap=timestamp-mStartTime;
		int result=getIntFromStream(inputStream,  2);
		if (type==DATA_TYPE_INIT){
			//初始化
			if (result!=INIT_SUCCESS){
				//初始化失败
			}else{
				mTalkCode=getStringFromStream(inputStream, 8);
				int keyLen=getIntFromStream(inputStream, 2);
				String key=getStringFromStream(inputStream, keyLen);
				mKey=EncryptTool.desDecrypt(key, KEY);
				getImgCheckCode(inputStream);
				result=0;
			}
			Log.d(tag,"===init finish,return code="+code);
		}else if (type==DATA_TYPE_GET_CHECKCODE){
			//获取验证码
			if (result!=GET_CHECKCODE_SUCCESS){
				//初始化失败
			}else{
				mTalkCode=getStringFromStream(inputStream, 8);
				result=0;
				getImgCheckCode(inputStream);
			}
			Log.d(tag,"===checkcode "+",return code="+code);
		}else if (type==DATA_TYPE_LOGIN){
			//登录
		    result = parseLoginData(inputStream, result, LOGIN_SUCCESS, true);
		}else if (type == DATA_TYPE_SEND_MSG_CODE){
            //短信登录时的发送短信验证码
		    result = parseLoginData(inputStream, result, SEND_MSG_CODE_SUCCESS, true);
        }else if (DATA_TYPE_MSG_LOGIN == type){
            //短信登录
            result = parseLoginData(inputStream, result, LOGIN_SUCCESS, false);
        }
		return result;
	}
	
	/**
	 * 解析图形验证码
	 * 
	 * <br>Created 2014-11-11 下午1:59:13
	 * @param inputStream      输入流
	 * @throws IOException     IO异常
	 * @author       linsj
	 */
	private void getImgCheckCode(InputStream inputStream) throws IOException{
        int checkCodeLen = getIntFromStream(inputStream, 2);
        Log.w("msg_login", mContext.getString(R.string.assistant_img_length) + checkCodeLen);
        if (checkCodeLen > 0) {
            // 当N2有数据时，即说明需要验证码
            getDrawableFromStream(inputStream);
        } else {
            getDrawableFromStream(null);
        }
	}
	
	/**
	 * 解析登录相关的返回数据包
	 * 
	 * <br>Created 2014-9-4 下午9:56:23
	 * @param inputStream      字节流
	 * @param iResult          服务端返回的结果标识
	 * @param iCorrectResult   该包对应的正确的结果结识
	 * @param bParseImgCheckCode   是否解析图形验证码，只有短信登录时不用
	 * @return                 新的结果标识，成功是为0，如果服务端返回了验证码，则返回ERR_NEED_INPUT_CHECK_CODE，否则将是数据包里的结果标识
	 * @throws IOException     IO异常
	 * @throws Exception       通用异常
	 * @author       linsj
	 */
    private int parseLoginData(InputStream inputStream, int iResult, final int iCorrectResult,
            boolean bParseImgCheckCode) throws IOException, Exception {
	    //短信登录时的发送短信验证码
        mTalkCode=getStringFromStream(inputStream, 8);
        int messageLen=getIntFromStream(inputStream, 2);
        String message = "";
        if (messageLen!=0){
            message=EncryptTool.desDecrypt(getStringFromStream(inputStream, messageLen), mKey);
        }
        if (iCorrectResult != iResult){
            mErrMsg=message;
        }else{
            //发送短信验证码成功
            iResult = 0;
            if(LOGIN_SUCCESS == iCorrectResult){
                // TODO 充值模块 启用：注释去掉
                int index = message.indexOf("&SDKToken=");
                if(index > 0) {
                    mCookie=message.substring(0, index);

                    String strParam = message.substring(index);
                    if(! TextUtils.isEmpty(strParam)) {
                        mToken = strParam.substring(strParam.indexOf("=")+1, strParam.indexOf("&", 1));

                        StarAppConfig.setConfig(StarAppConfig.CONFIG_PAY_TOKEN, mToken);
                    }
                } else {
                    mCookie=message;
                }
            }
        }
        
        //解析验证码
        if(bParseImgCheckCode){
            getImgCheckCode(inputStream);
        }
        
        return iResult;
	}
	
	public BitmapDrawable getDrawable(){
		return mDrawable;
	}
	
	public boolean hasCheckcode(){
		return mDrawable!=null;
	}
	
	
	private  int getIntFromStream(InputStream inputStream,int len)throws IOException {
		byte[] buffer=new byte[len];
		try {
			inputStream.read(buffer, 0, len);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EncryptTool.byteArrayToInt(buffer);
	}
	
	private  long getLongFromStream(InputStream inputStream,int len)throws IOException {
		byte[] buffer=new byte[len];
		try {
			inputStream.read(buffer, 0, len);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EncryptTool.byteArrayToLong(buffer);
	}
	
	private  String getStringFromStream(InputStream inputStream,int len)throws IOException {
		byte[] buffer=new byte[len];
		try {
			inputStream.read(buffer, 0, len);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new String(buffer,"UTF-8");
	}
	
	/**
	 * 派发图形验证码
	 * 
	 * <br>Created 2014-9-23 下午5:46:38
	 * @param inputStream      输入流
	 * @throws IOException     IO异常
	 * @author       linsj
	 */
	private void getDrawableFromStream(InputStream inputStream) throws IOException{
		try {
		    if(null == inputStream){
		        ((Activity) mContext).runOnUiThread(new Runnable() {
	                public void run() {
	                    NdMiscCallbackListener.onGetCheckcodeFinish(true, 0, "", null);
	                }
	            });
		    }else{
		        mDrawable=new BitmapDrawable(inputStream);
	            ((Activity) mContext).runOnUiThread(new Runnable() {
	                public void run() {
	                    NdMiscCallbackListener.onGetCheckcodeFinish(true, 0, "", mDrawable);
	                }
	            });
		    }			
		} catch (Exception e) {
		}
	}
	
//	private byte[] streamToByte(InputStream stream) throws IOException {
//		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
//		byte[] buff = new byte[100]; // buff���ڴ��ѭ����ȡ����ʱ���
//		int rc = 0;
//		while ((rc = stream.read(buff, 0, 100)) > 0) {
//			swapStream.write(buff, 0, rc);
//		}
//		byte[] in_b = swapStream.toByteArray(); // in_bΪת��֮��Ľ��
//		return in_b;
//	}
	
	private void getErrmsgFromCode(int result){
		if (result==0){
			mErrMsg="";
			return;
		}
		if (result==-1){
			//errmsg已写好
			//Log.d(tag, mErrMsg);
			return;
		}
		if (result<1000){
			mErrMsg= mContext.getString(R.string.assistant_http_error)+mErrorCode;
			//Log.d(tag, mErrMsg);
			return;
		}
		switch (result) {
		case RESPONSE_TYPE_ERROR:
			//Log.d(tag, mErrMsg);
			break;
		case 11007:
			mErrMsg= mContext.getString(R.string.assistant_code_error);
			break;
		case 11009:
			mErrMsg = mContext.getString(R.string.assistant_jay_error);
			break;
		case 11010:
			mErrMsg=mContext.getString(R.string.assistant_inf_over);
			break;
		case 20181:
			mErrMsg =  mContext.getString(R.string.assistant_jay_error);
			break;
		case 20183:
		    mErrMsg =  mContext.getString(R.string.assistant_jay_error);
			break;
		case 20001:
			mErrMsg= mContext.getString(R.string.assistant_accout_unreg);
			break;
		case 20005:
		    mErrMsg = mContext.getString(R.string.assistant_jay_error);
			break;
		case 20006:
			mErrMsg= mContext.getString(R.string.assistant_data_packet);
			 break;
		case 20042:
			mErrMsg= mContext.getString(R.string.assistant_pwd_error);
			break;
		case 20049:
			mErrMsg= mContext.getString(R.string.assistant_login_limit);
			break;
		case 20051:
            mErrMsg= mContext.getString(R.string.assistant_pwd_length_error);
			break;
		case ERR_TYPE_IMG_CODE_ERR:
            mErrMsg= mContext.getString(R.string.assistant_code_fail_error);
			break;
		case 20092:
            mErrMsg= mContext.getString(R.string.assistant_account_activation);
		case 20243:
		case 30312:
            mErrMsg= mContext.getString(R.string.assistant_msg_code_send_limit);
		case 30313:
            mErrMsg= mContext.getString(R.string.assistant_msg_code_limit);
			break;
		case 30605:
            mErrMsg= mContext.getString(R.string.assistant_phone_not_bind_99);
            break;
//		case ERR_NEED_INPUT_CHECK_CODE:
//            mErrMsg="请输入验证码";
//            break;
		default:
			try {
				mErrMsg=mContext.getString(mErrorCode);	
			} catch (Exception e) {
				mErrMsg=mContext.getString(R.string.assistant_unkown)+result;
			}
			break;
		}
		//Log.d(tag, mErrMsg);
	}
	
	private void getMsgLoginErrmsgFromCode(int result){
        switch (result) {
        case 20001:
            mErrMsg=mContext.getString(R.string.assistant_accout_unreg);
            break;
        case 20042:
            mErrMsg=mContext.getString(R.string.assistant_code_fail_error);
            break;
        case 20051:
            mErrMsg=mContext.getString(R.string.assistant_code_length_error);
            break;
        case ERR_TYPE_IMG_CODE_ERR:
            mErrMsg=mContext.getString(R.string.assistant_code_fail_error);
            break;
        default:
            getErrmsgFromCode(result);
            break;
        }
    }
}
